/**
 * Created by lijizhuang on 16/9/1.
 */
define(['jquery', 'underscore', 'backbone', 'common', 'url', 'text!modules/registerAndLogin/loginView.html', 'models/registerAndLogin/loginInfo'],
    function ($, _, Backbone, Common, Url, loginViewTemplate, LoginInfo) {
        var loginView = Backbone.View.extend({
            template: _.template(loginViewTemplate),

            initialize: function () {
                _loginView = this;
                this.model.bind('change:loggedIn', this.render, this);
            },

            events: {
                "submit .login-content": "onLoginSubmit",
            },

            onLoginSubmit: function (e) {
                e.preventDefault();
                $("input[type='submit']").attr('disabled', "true");
                $("input[type='submit']").val("正在登录...");
                _loginView.$el.find('#validMess').html('');
                //验证成功后设置token
                //this.model.setToken('token');
                var loginInfo = new LoginInfo();
                //侦听模型验证失败的事件
                loginInfo.on('invalid', function (model, error) {
                    _loginView.$el.find('#validMess').html(error);
                });

                loginInfo.set({
                    userName: $('#username').val(),
                    password: $('#password').val(),
                    store30Days: $('#chkAutoLogin').is(':checked')
                }, { 'validate': true });

                Common.sendAjaxRequest(Url.login, loginInfo.attributes, function (data) {
                    window.location.href = "Home/Index";
                }, function (data) {
                    if (data.Content && data.Content.length > 0) {
                        _loginView.$el.find('#validMess').html(data.Content);
                        $("input[type='submit']").removeAttr("disabled");
                        $("input[type='submit']").val("登 录");
                    }
                }, false);
            },

            render: function () {
                if (this.model.get('loggedIn')) {
                    //跳转到看板
                } else {
                    $(this.el).empty().html(this.template(this.model));
                }
                return this;
            }
        });

        return loginView;
    });